<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-区域`"
		width="500px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="编号" prop="code">
						<el-input v-model="ruleForm.code" placeholder="编号" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="名称" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="负责人">
						<jk-search-select
							v-model="ruleForm.leaderId"
							placeholder="负责人"
							only-key="leaderId"
							query-name="leaderName"
							class="width-100-percent"
							:params-data="ruleForm"
							:query-search-async="querySearchAsyncOfSelectEmp"
							@on-select="onSelectEmpChange"
							@on-click-icon="onSelectEmpIcon"
						></jk-search-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="排序">
						<jk-number-input v-model="ruleForm.sortNum" placeholder="排序" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<select-emp-dialog
			title="负责人"
			:dialog-state="selectEmpDialogState"
			@on-confirm="onConfirmBtnOfSelectUserDialog"
			@on-visible-change="onVisibleChangeOfSelectEmpDialog"
		></select-emp-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import {
        systemWorkshopCreate,
        systemWorkshopUpdate,
        systemWorkshopGet
    } from '../../../api/basicData/workshop';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import { getEmpPage } from '../../../api/system/emp';
    import { pageConfig } from '../../../utils/jk/jk-tool';
    import selectEmpDialog from '../../technology/order/components/remote-search-emp-input/radio-select-emp-dialog';
    export default {
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        components: { selectEmpDialog },
        mixins: [calHeight],
        data() {
            return {
                selectEmpDialogState: false,
                typeList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    code: '',
                    name: '',
                    sortNum: 1,
                    status: 1,
                    leaderId: null,
                    leaderName: ''
                },
                rules: {
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    leaderId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onVisibleChangeOfSelectEmpDialog(e) {
                this.selectEmpDialogState = e;
            },
            onConfirmBtnOfSelectUserDialog(e) {
                if (Object.keys(e).length) {
                    this.selectEmpDialogState = false;
                    this.setDependentDataSalesman(e);
                }
            },
            onSelectEmpIcon() {
                this.selectEmpDialogState = true;
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.setDependentDataSalesman(e);
                }
            },
            setDependentDataSalesman(e) {
                this.$set(this.ruleForm, 'leaderId', e.id);
                this.$set(this.ruleForm, 'leaderName', e.name);
            },
            querySearchAsyncOfSelectEmp(queryString) {
                return getEmpPage({
                    onJob: true,
                    nameOrCode: queryString,
                    pageNo: 1,
                    pageSize: pageConfig.remotePageSize
                }).then(res => {
                    if (res.data.status === 200) {
                        return res.data.res.map(x => {
                            return {
                                value: x.name,
                                ...x
                            };
                        });
                    }
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? systemWorkshopCreate : systemWorkshopUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return systemWorkshopGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'GQ_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.typeList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getTypeListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
